<template>
  <div style="height: 100%">
    <a-spin :spinning="isTableLoading" wrapperClassName="spinning-container">
      <div class="header-container" ref="headerContainer">
        <page-header :title="l('ApkManagement')"></page-header>
        <a-card :bordered="false">
          <a-form :layout="'vertical'" @submit.prevent="getSearchData">
            <a-row :gutter="8">
              <!-- 搜索 -->
              <a-col :sm="24">
                <a-form-item>
                  <a-input-search
                    name="filterText"
                    :placeholder="l('SearchWithThreeDot')"
                    @search="getSearchData"
                    enterButton
                    v-model:value="filterText"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
          <!-- 操作部分 -->
          <a-row :gutter="8">
            <a-col :md="20" :sm="12">
              <!-- 添加用户 -->
              <a-button
                type="primary"
                v-if="isGranted('Pages.ApkManagement.Create')"
                @click="createOrEdit()"
              >
                <plus-outlined />
                <span>{{ l('CreateApkManagement') }}</span>
              </a-button>
              <!-- 批量删除 -->
              <a-button
                type="'danger'"
                v-if="isGranted('Pages.ApkManagement.Delete')"
                @click="batchDelete()"
              >
                <delete-outlined />
                <span>{{ l('BatchDelete') }}</span>
              </a-button>
            </a-col>
          </a-row>

          <!-- 数据部分 -->
          <div class="my-md">
            <a-alert :type="'info'" :showIcon="true">
              <template #message>
                <span v-html="l('GridSelectedXItemsTips', selectedCount)"></span>
                <a @click="restCheckStatus()" class="ml-md">{{ l('ClearEmpty') }}</a>
                <a-divider type="vertical"></a-divider>
                <a @click="refresh()">{{ l('Refresh') }}</a>
              </template>
            </a-alert>
          </div>
        </a-card>
      </div>
      <!-- 表格 -->
      <div class="table-container">
        <a-table
          size="middle"
          :scroll="{ x: tableWidthScroll, y: tableHeightScroll }"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data-source="dataList"
          :pagination="{
            total: totalItems,
            current: pageNumber,
            pageSize: pageSize,
            showTotal: showTotalInfo,
            showQuickJumper: true,
            showSizeChanger: true,
            change: pageNumberChange,
            showSizeChange: pageNumberChange,
            pageSizeOptions: pageSizeOptions,
            size: 'middle',
          }"
          :rowSelection="{
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange,
            checkAll: checkAll,
          }"
          @change="tableChange"
        >
          <!-- tbody插槽 -->
          <template #bodyCell="{ column, record }">
            <!-- 版本 -->
            <template v-if="column.key === 'appRevision'">
              <p>{{ record.appRevision }}</p>
            </template>

            <!-- 最新版本 -->
            <template v-if="column.key === 'isNewRevision'">
              <a class="isNewRevision">
                <check-outlined v-if="record.isNewRevision" />
                <close-outlined v-else />
              </a>
            </template>

            <!-- 地址 -->
            <template v-if="column.key === 'fileNamePath'">
              <p>{{ record.fileNamePath }}</p>
            </template>

            <!-- 创建时间 -->
            <template v-if="column.key === 'creationTime'">
              <p>{{ _moment(record.creationTime) }}</p>
            </template>

            <!-- 操作列 -->
            <template v-if="column.key === 'actions'">
              <div>
                <!-- 复制 -->
                <a class="table-edit" @click="copy(record)">
                  <edit-outlined />
                  {{ l('CopyUrl') }}
                </a>
                <!-- 修改 -->
                <a
                  class="table-edit"
                  @click="createOrEdit(record)"
                  v-if="isGranted('Pages.ApkManagement.Edit')"
                >
                  <edit-outlined />
                  {{ l('Edit') }}
                </a>
                <!-- 删除 -->
                <template v-if="isGranted('Pages.ApkManagement.Delete')">
                  <a-divider type="vertical" />
                  <a-popconfirm
                    placement="top"
                    :ok-text="l('Ok')"
                    :cancel-text="l('Cancel')"
                    @confirm="deleteItem(record)"
                  >
                    <template #title>{{ l('ConfirmDeleteWarningMessage') }}</template>
                    <a>
                      <delete-outlined />
                      {{ l('Delete') }}
                    </a>
                  </a-popconfirm>
                </template>
              </div>
            </template>
          </template>
        </a-table>
      </div>
    </a-spin>
  </div>
</template>

<script lang="ts">
  import { defineComponent } from 'vue';
  import { IPagedRequestDto } from '/@/shared/component-base/interfaces';
  import { PagedListingComponentBase } from '/@/shared/component-base';
  import {
    ApkManagementListDto,
    ApkManagementServiceProxy,
  } from '/@/shared/service-proxies/service-proxies';
  import { CheckOutlined, CloseOutlined } from '@ant-design/icons-vue';
  import { ColumnType } from 'ant-design-vue/lib/table';
  import CreateOrEditApkManagement from './create-or-edit-apk-management/create-or-edit-apk-management.vue';
  export default defineComponent({
    name: 'apk-managements',
    components: {
      CreateOrEditApkManagement,
      CheckOutlined,
      CloseOutlined,
    },
    mixins: [PagedListingComponentBase],
    data() {
      return {
        /** 用户api */
        apkManagementService: new ApkManagementServiceProxy(),
        /** 数据 */
        dataList: [] as ApkManagementListDto[],
        copyText: '',
      };
    },
    methods: {
      /**
       * 获取数据
       */
      fetchDataList(request: IPagedRequestDto, finishedCallback?: () => void) {
        this.apkManagementService
          .getPaged(this.filterText, request.sorting, request.maxResultCount, request.skipCount)
          .finally(() => {
            finishedCallback!();
          })
          .then((res) => {
            this.showPaging(res);
          });
      },
      /**
       * 单个删除
       */
      deleteItem(item: ApkManagementListDto) {
        this.isTableLoading = true;
        this.apkManagementService
          .delete(item.id)
          .finally(() => {
            this.isTableLoading = false;
          })
          .then(() => {
            this.refreshGoFirstPage();
            this.notify.success(this.l('SuccessfullyDeleted'));
          });
      },
      /**
       * 批量删除
       */
      batchDelete() {
        if (this.selectedCount <= 0) {
          this.message.warn(this.l('PleaseSelectAtLeastOneItem'));
          return;
        }
        this.message.confirm(
          this.l('ConfirmDeleteXItemsWarningMessage', this.selectedCount),
          '',
          (res: any) => {
            if (res) {
              const ids = [...this.selectedRowKeys];
              this.isTableLoading = true;
              this.apkManagementService
                .batchDelete(ids)
                .finally(() => {
                  this.isTableLoading = false;
                })
                .then(() => {
                  this.refreshGoFirstPage();
                  this.notify.success(this.l('SuccessfullyDeleted'));
                });
            }
          },
        );
      },
      /**
       * 复制代码或者链接
       */
      copy(res) {
        var textareaC = document.createElement('textarea');
        textareaC.setAttribute('readonly', 'readonly'); //设置只读属性防止手机上弹出软键盘
        textareaC.value = res.fileNamePath;
        document.body.appendChild(textareaC); //将textarea添加为body子元素
        textareaC.select();
        var res = document.execCommand('copy');
        document.body.removeChild(textareaC); //移除DOM元素
        this.notify.success(this.l('CopySuccessfully'));
      },
      getColumns(): ColumnType<ApkManagementListDto>[] {
        return [
          {
            title: 'No',
            customRender: ({ index }) => {
              const a = (this.pageNumber - 1) * this.pageSize + (index + 1);
              return a;
            },
            width: 60,
            fixed: 'left',
          },
          {
            title: this.l('ApkManagementAppRevision'),
            dataIndex: 'appRevision',
            key: 'appRevision',
            width: 200,
            ellipsis: true,
            sorter: {
              multiple: 0,
            },
          },
          {
            title: this.l('IsNewRevision'),
            dataIndex: 'isNewRevision',
            key: 'isNewRevision',
            width: 200,
            ellipsis: true,
          },
          {
            title: this.l('Address'),
            dataIndex: 'fileNamePath',
            key: 'fileNamePath',
            width: 200,
            ellipsis: true,
            sorter: {
              multiple: 0,
            },
          },
          // 邮箱验证
          {
            title: this.l('ApkManagementDescription'),
            dataIndex: 'description',
            key: 'description',
            width: 135,
            ellipsis: true,
            sorter: {
              multiple: 0,
            },
          },
          {
            title: this.l('CreationTime'),
            dataIndex: 'creationTime',
            key: 'creationTime',
            width: 200,
            ellipsis: true,
            sorter: {
              multiple: 0,
            },
          },
          {
            title: this.l('Actions'),
            dataIndex: 'actions',
            key: 'actions',
            width: 250,
            ellipsis: true,
            fixed: 'right',
          },
        ];
      },
      /**
       * 添加 修改
       */
      createOrEdit(item?: ApkManagementListDto) {
        this.modalHelper
          .create(
            CreateOrEditApkManagement,
            {
              id: item != null ? item.id : null,
            },
            {
              width: '400px',
            },
          )
          .subscribe((res) => {
            if (res) {
              this.refresh();
            }
          });
      },
    },
  });
</script>
